package hsl.study.controller;


import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @Description:
 * @Author: hsl
 * @CreateDate: 2025/8/1 10:04
 * @Version: 1.0
 */


@RestController
@RequestMapping("/blt2v")
public class Text2VoiceController {

    // voice model
    public static final String BAILIAN_VOICE_MODEL = "cosyvoice-v2";
    // voice timber
    public static final String BAILIAN_VOICE_TIMBER = "longyingtian";//龙应甜

    @GetMapping("/voice")
    public String voice(@RequestParam(name = "msg", defaultValue = "温馨提醒，支付宝到账100万元，请注意查收") String msg) {
        // 语音参数配置
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(System.getenv("LANGCHAIN_TONGYI"))
                .model(BAILIAN_VOICE_MODEL)
                .voice(BAILIAN_VOICE_TIMBER)
                .build();

        // 语音生成对象
        SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(param, null);
        // 字节流语音
        ByteBuffer byteBuffer = speechSynthesizer.call(msg);
        String filePath = "D:\\voice\\" + System.currentTimeMillis() + ".mp3";

        try {
            FileOutputStream stream = new FileOutputStream(new File(filePath));
            stream.write(byteBuffer.array());
        } catch (IOException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        }
        return filePath;
    }
}
